package com.farm.web.filter.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.farm.core.time.TimeTool;
import com.farm.parameter.FarmParameterService;
import com.farm.web.WebUtils;
import com.farm.web.log.WcpLog;
import com.wuc.client.WucEventClient;
import com.wuc.client.domain.EventData;
import com.wuc.client.domain.EventRUser;
import com.wuc.client.domain.Values;

/**
 * 收集和处理pvuv数据
 * 
 * @author macpl
 *
 */
public class WebPuvCounter {
	private static String YMD = null;
	private static int pv = 0;
	private static Set<String> uv = new HashSet<String>();

	/**
	 * 触发一个访问事件
	 * 
	 * @param request
	 */
	public static void onVisit(HttpServletRequest request) {
		try {
			// cym为提交评率默认每日yyyyMMdd
			String cym = TimeTool.getTimeDate(new Date(), "yyyyMMdd");
			if (YMD == null) {
				YMD = cym;
			}
			{
				// 合计
				pv = pv + 1;
				uv.add(WebUtils.getCurrentIp(request));
			}
			if (!YMD.equals(cym)) {
				{
					access();
				}
				{
					// 清理
					YMD = cym;
					pv = 0;
					uv.clear();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void access() {
		WcpLog.info("pv=" + pv + ",uv=" + uv.size(), "none", "none");
		if (FarmParameterService.getInstance().getParameterBoolean("config.wuc.event.able") ) {
			try {
				// 数据提交
				WucEventClient client = new WucEventClient(
						FarmParameterService.getInstance().getParameter("config.wuc.api.base.url"),
						FarmParameterService.getInstance().getParameter("config.wuc.api.secret"),
						FarmParameterService.getInstance().getParameter("config.wuc.api.loginname"),
						FarmParameterService.getInstance().getParameter("config.wuc.api.password"));
				Values vals = new Values();
				vals.setInt1(pv, "pv");
				vals.setInt2(uv.size(), "uv");
				String ctime = TimeTool.getTimeDate(new Date(), "yyyyMMddHHmm");
				client.recordEvent(new EventData(ctime, ctime, "WEB_VISIT_STAT", "访问量统计", null,
						FarmParameterService.getInstance().getParameter("config.wuc.sysid"), TimeTool.getTimeDate14(),
						vals), new ArrayList<EventRUser>());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
